import pandas as pd
import hashlib
from data_storage import DataStorage

class UserManagement:
    def __init__(self):
        self.data_storage = DataStorage()

    def hash_password(self, password):
        return hashlib.sha256(password.encode()).hexdigest()

    def login_user(self, username, password):
        users_df = self.data_storage.read_users()
        user = users_df.loc[users_df['username'] == username].squeeze()
        if user.empty:
            return False, "User not found", None
        if user['password_hash'] == self.hash_password(password):
            return True, "Login successful", user['role']
        else:
            return False, "Incorrect password", None

    def register_user(self, username, password, role='user'):
        users_df = self.data_storage.read_users()
        if username in users_df['username'].values:
            return False, "Username already exists"
        new_id = len(users_df) + 1
        new_user = {
            'id': new_id,
            'username': username,
            'password_hash': self.hash_password(password),
            'role': role
        }
        new_row = pd.DataFrame([new_user])
        users_df = pd.concat([users_df, new_row], ignore_index=True)
        self.data_storage.write_users(users_df)
        return True, "User registered successfully"